'''
二维码扫描代码
'''
import time
import cv2
import numpy as np
# import zbar
import pyzbar.pyzbar as pyzbar

# 基于轮廓定位的qr位置
def find_code(img):
    # 高斯滤波
    blur = cv2.GaussianBlur(img,(5,5),0)
    # 灰度图像
    gray = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)
    # 二值化
    ret,th = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
    # 形态学操作
    mask=cv2.erode(th,None,iterations=4)
    mask=cv2.dilate(mask,None,iterations=4)
	# 图像反色
    cv2.bitwise_not(mask, mask)
    # 寻找轮廓
    contours,hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    # 寻找最大的QR码的位置
    if len(contours)>0:
        cnt = max(contours, key=cv2.contourArea)
        x,y,w,h = cv2.boundingRect(cnt)
        img = cv2.rectangle(img,(x-15,y-15),(x+w+15,y+h+15),(0,255,0),3)
		# 裁剪图片
        img_ROI = img[y-15:y+h+15, x-15:x+w+15]
    else:
        # 没找到qr码
        img_ROI = img

    return img_ROI

# main函数
if __name__ == '__main__':

    font = cv2.FONT_HERSHEY_SIMPLEX # openCV 字体

    cap = cv2.VideoCapture(0)  # 0: use CSI camera,1：use USB camera
    cap.set(3,480) # set Width
    cap.set(4,360) # set Height
    if(not cap.isOpened()):
        print("[camera.py:cam]:can't open this camera")
    
    while(True):
        # 读入图片
        ret, img = cap.read() 
        # 转灰度
        img_ROI_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 解码
        barcodes = pyzbar.decode(img_ROI_gray) # 返回识别到的多个二维码对象的列表

        area = 0 # 面积
        max_barcode = None # 最大的二维码
        # 选出面积最大的二维码
        for barcode in barcodes:
            (x,y,w,h) = barcode.rect  # 坐标格式：[横坐标，纵坐标，长度，宽度]  单位：像素
            if (area <= w*h):
                area = w*h
                max_barcode = barcode
        # 处理最大的二维码信息
        if (max_barcode != None):
            # 条形码数据为字节对象，所以如果我们想在输出图像上
            # 画出来，就需要先将它转换成字符串
            barcodeData = max_barcode.data.decode("utf-8")
            barcodeType = max_barcode.type
            text = "{} ({})".format(barcodeData, barcodeType)
            # 获取二维码坐标
            (x,y,w,h) = max_barcode.rect  # 坐标格式：[横坐标，纵坐标，长度，宽度]  单位：像素
            print("location: ", max_barcode.rect)
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            # 打印字符在图片上
            cv2.putText(img, text , (20,100),font,1,(0,255,0),4) 
            # 向终端打印条形码数据和条形码类型
            print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))

        # 显示
        cv2.imshow('image', img)
        if (cv2.waitKey(1)) == ord('q'):
            break
        time.sleep(1) # 隔一秒，读一次图片
    # 释放资源
    cap.release()
    cv2.destroyAllWindows() 